package com.tripspins.app.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tripspins.app.R;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.CurrentWeather;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Route;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.helper.FILE_TYPE;
import com.tripspins.app.helper.FileHelper;
import com.tripspins.app.helper.MapsAPIHelper;
import com.tripspins.app.helper.ThumbnailsHelper;
import com.tripspins.app.interfaces.OnFragmentInteractionListener;
import com.tripspins.app.interfaces.OnTaskCompleted;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.HashMap;

public class MapDetailsTripFragment extends Fragment implements OnTaskCompleted{

    private OnFragmentInteractionListener mListener;
    private Trip trip;
    private static final String ARG_TRIP = "arg_trip";
    TextView tripTitle;
    TextView tripDays;
    TextView tripCountPins;
    TextView tripCountAttachments;
    LinearLayout tripScrollAttachments;
    RelativeLayout tripDetailLayout;
    private SupportMapFragment mapFragment;
    private MapsAPIHelper mapsHelper;
    private HashMap<String,Pin>  markersMap;
    private Pin lastPin;


    public static MapDetailsTripFragment newInstance(Trip trip) {
        MapDetailsTripFragment fragment = new MapDetailsTripFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_TRIP, trip);
        fragment.setArguments(args);
        return fragment;
    }
    public MapDetailsTripFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            trip = getArguments().getParcelable(ARG_TRIP);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View viewRoot = inflater.inflate(R.layout.fragment_map_details, container, false);
        mapFragment = SupportMapFragment.newInstance();
        FragmentManager fragmentManager = getChildFragmentManager();
        if(fragmentManager.getFragments() == null)
            fragmentManager.beginTransaction().add(R.id.map_details_holder,mapFragment).commit();
        markersMap = new HashMap<String, Pin>();
        mapsHelper = new MapsAPIHelper(this);
        getActivity().invalidateOptionsMenu();
        loadViews(viewRoot);


        return viewRoot;
    }

    private void loadViews(View viewRoot) {
        tripTitle = (TextView)viewRoot.findViewById(R.id.map_trip_title);
        tripDays = (TextView)viewRoot.findViewById(R.id.map_trip_days);
        tripCountPins = (TextView)viewRoot.findViewById(R.id.map_trip_count_pins);
        tripCountAttachments = (TextView)viewRoot.findViewById(R.id.map_trip_count_attachments);
        tripScrollAttachments = (LinearLayout)viewRoot.findViewById(R.id.map_trip_attachments_list);

        tripTitle.setText(trip.getDescription());
        tripCountAttachments.setText(String.valueOf(trip.getCountAttachments()));
        tripCountPins.setText(String.valueOf(trip.getPins().size()));
        int dayCount = trip.getCountDays();
        if (dayCount == 1)
            tripDays.setText( String.valueOf(dayCount) + " " + getActivity().getString(R.string.day_on_the_road));
        else
            tripDays.setText( String.valueOf(dayCount) + " " + getActivity().getString(R.string.days_on_the_road));

        loadAttachmentsThumbnails(trip.getPins());

    }

    @Override
    public void onTaskCompleted(Route route) {
        boolean moveCenter = route != null && route.getPoints().size() > 0;
        trip.setRoute(route);
        if(mapFragment.getMap() != null) {

            try {
                PolylineOptions rectOptions = new PolylineOptions();
                rectOptions.color(Color.parseColor("#C95E18"));
                for(LatLng latLng: route.getPoints())
                {
                    rectOptions.add(latLng);
                }
                /*for (Pin pin : trip.getPins()) {
                    rectOptions.add(pin.getLatLng());
                }*/
                Polyline rota = mapFragment.getMap().addPolyline(rectOptions);
                LatLngBounds bounds = new LatLngBounds(trip.getRoute().getBounds().get(1), trip.getRoute().getBounds().get(0));
                CameraUpdate center = CameraUpdateFactory.newLatLngBounds(bounds, 150);

                if (moveCenter) {
                    mapFragment.getMap().moveCamera(center);
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onTaskCompleted(CurrentWeather w) {

    }

    @Override
    public void onTaskCompleted(Bitmap b) {

    }

    @Override
    public void onTaskCompleted(Attachment att) {

    }

    private static class AuxParam
    {
        public ArrayList<Pin> pins;
        public LinearLayout scroll;
        public Context context;
    }
    private void loadAttachmentsThumbnails(ArrayList<Pin> pins) {

        tripScrollAttachments.removeAllViews();
        AuxParam param = new AuxParam();
        param.pins = pins;
        param.scroll = tripScrollAttachments;
        param.context = getActivity();

        new AsyncTask<AuxParam,Void, ArrayList<View>>()
        {
            AuxParam param;
            ArrayList<View> list;

            @Override
            protected ArrayList<View> doInBackground(AuxParam... params) {
                param = params[0];
                ImageView thumbnail;
                list = new ArrayList<View>();
                for(Pin p : param.pins)
                {
                    for(Attachment a : p.getAttachments())
                    {
                        //TODO incluir outros thumbnails
                        if(a.getFileType() == FILE_TYPE.IMAGE ||a.getFileType() == FILE_TYPE.VIDEO)
                        {
                            final Attachment att = a;
                            thumbnail = new ImageView(param.context);
                            thumbnail.setMaxHeight(400);
                            thumbnail.setMaxWidth(400);
                            thumbnail.setScaleType(ImageView.ScaleType.FIT_START);
                            thumbnail.setPadding(0,3,3,0);
                            try {
                                thumbnail.setImageURI(Uri.parse(a.getThumbnailPath()));
                            }catch (Throwable e1){
                                System.gc();
                                try{
                                    thumbnail.setImageURI(Uri.parse(a.getThumbnailPath()));

                                }catch (Throwable e2){
                                    Log.e("TP",e2.getMessage());
                                }
                            }
                            thumbnail.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent();
                                    intent.setAction(Intent.ACTION_VIEW);
                                    if (att.getFileType() == FILE_TYPE.IMAGE )
                                        intent.setDataAndType(Uri.parse("file://" + att.getPath()), "image/*");
                                    else intent.setDataAndType(Uri.parse("file://" + att.getPath()), "video/*");
                                    getActivity().startActivity(intent);
                                }
                            });
                            list.add(thumbnail);
                        }
                    }
                }
                return list;
            }

            @Override
            protected void onPostExecute(ArrayList<View> views) {
                super.onPostExecute(views);
                for (View v : views)
                    tripScrollAttachments.addView(v);

            }
        }.execute(param);

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public void onDestroyView() {
        super.onDestroyView();
        getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mapFragment.getMap() != null) {
            lastPin = trip.getPinFinish();
            for (Pin p : trip.getPins()) {
                MarkerOptions markerOptions = mapsHelper.getMarker(p);
                Marker marker = mapFragment.getMap().addMarker(markerOptions);
                markersMap.put(marker.getId(), p);
            }

            mapFragment.getView().getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if(mapFragment.getMap() != null) {
                                CameraUpdate center = null;
                                LatLngBounds bound = new LatLngBounds(lastPin.getLatLng(), lastPin.getLatLng());
                                center = CameraUpdateFactory.newLatLngZoom(lastPin.getLatLng(), 12.0f);
                                mapFragment.getMap().moveCamera(center);
                            }
                        }
                    });
            mapsHelper.getRoute(trip);
        }
    }


    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        menu.clear();
        menuInflater.inflate(R.menu.menu_map_on_the_road, menu);
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_view_as_list:
                mListener.viewTripAsList(trip);
                break;

        }
        return true;
    }
}
